package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.OverflowListDao;
import com.atguigu.jxc.dao.OverflowListGoodsDao;
import com.atguigu.jxc.entity.DamageList;
import com.atguigu.jxc.entity.DamageListGoods;
import com.atguigu.jxc.entity.OverflowList;
import com.atguigu.jxc.entity.OverflowListGoods;
import com.atguigu.jxc.service.GoodsService;
import com.atguigu.jxc.service.OverflowListGoodsService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Type;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author dxt
 * @create 2025-07-16-21:15
 */
@Service
public class OverflowListGoodsServiceImpl implements OverflowListGoodsService {

    @Autowired
    private OverflowListDao overflowListDao;

    @Autowired
    private OverflowListGoodsDao overflowListGoodsDao;

    @Autowired
    private GoodsService goodsService;

    /**
     * 保存报溢单
     * @param overflowList 报溢单
     * @param overflowListGoodsStr 报溢单商品
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(OverflowList overflowList, String overflowListGoodsStr) {
        Gson gson = new Gson();
        Type listType = new TypeToken<List<OverflowListGoods>>(){}.getType();
        List<OverflowListGoods> overflowListGoodsList = gson.fromJson(overflowListGoodsStr, listType);
        overflowListDao.insert(overflowList);
        for (OverflowListGoods overflowListGoods : overflowListGoodsList) {
            overflowListGoodsDao.save(overflowList, overflowListGoods);
            goodsService.addStock(overflowListGoods.getGoodsId(), overflowListGoods.getGoodsNum());
        }
    }

    /**
     * 查询报溢单
     * @param sTime 开始时间
     * @param eTime 结束时间
     * @return
     */
    @Override
    public Map<String, Object> getList(String sTime, String eTime) {
        HashMap<String, Object> resultMap = new HashMap<>();
        List<OverflowList> list = overflowListDao.selectList(sTime, eTime);
        resultMap.put("rows", list);
        return resultMap;
    }

    /**
     * 查询报损单商品
     * @param overflowListId 报溢单Id
     * @return
     */
    @Override
    public Map<String, Object> getGoodsList(Integer overflowListId) {
        HashMap<String, Object> resultMap = new HashMap<>();
        List<OverflowListGoods> overflowListGoodsList = overflowListGoodsDao.selectGoodsList(overflowListId);
        resultMap.put("rows", overflowListGoodsList);
        return resultMap;
    }
}
